<template>
  <a-spin :spinning="cardLoading">
    <a-row :gutter="20">
      <a-col :span="5">
        <a-card :bordered="false">
          <a-tree
            v-model="checkedKeys"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            @expand="onExpand"
            @select="onSelect"
            :replace-fields="replaceFields"
          />
        </a-card>
      </a-col>
      <a-col :span="19">
        <x-card v-if="hasPerm('gardenhouse:page')">
          <div slot="content" class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="20">
                <a-col :md="4" :sm="24">
                  <a-month-picker placeholder="选择月份" :format="monthFormat" @change="onChange" />
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="幼儿名称">
                    <a-input v-model="queryParam.ChildName" allow-clear placeholder="请输入幼儿名称" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button type="primary" @click="$refs.guizeshezhi.edit(true)">考勤规则设置</a-button>
                  <x-down ref="batchExport" @batchExport="batchExport" />
                </a-col>
              </a-row>
            </a-form>
          </div>
        </x-card>
        <a-card :bordered="false">
          <s-table
            ref="table"
            :columns="columns"
            :data="loadData"
            :alert="options.alert"
            :rowKey="record => record.id"
            :rowSelection="options.rowSelection"
          >
            <span slot="action" slot-scope="text, record">
              <a v-if="hasPerm('coursetype:edit')" @click="$refs.addForm.add(record)">详情</a>
            </span>
          </s-table>
          <add-form ref="addForm" @ok="handleOk" />
          <edit-form ref="editForm" @ok="handleOk" />
          <guizeshezhi ref="guizeshezhi" @ok="handleOk"></guizeshezhi>
          <kaoqintongji ref="kaoqintongji" @ok="handleOk"></kaoqintongji>
        </a-card>
      </a-col>
    </a-row>
  </a-spin>
</template>

<script>
import { STable, XCard, XDown } from '@/components'
import { courseTypePage, courseTypeDelete } from '@/api/modular/garden/courseManage'
import { sysPosList } from '@/api/modular/garden/classManage'
import { childAttendancePage,ChildrensRecordExport } from '@/api/modular/garden/kaoqin'
import { getOrgPage, getOrgTree } from '@/api/modular/system/orgManage'
import addForm from './addForm'
import editForm from './editForm'
import guizeshezhi from './guizeshezhi'
import kaoqintongji from './kaoqintongji'

export default {
  components: {
    XDown,
    XCard,
    STable,
    addForm,
    editForm,
    guizeshezhi,
    kaoqintongji
  },

  data() {
    return {
      // 查询参数
      queryParam: {},
      cardLoading: false,
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'childName'
        },
        {
          title: '应出',
          dataIndex: 'should'
        },
        {
          title: '实出',
          dataIndex: 'reality'
        },
        {
          title: '未签到',
          dataIndex: 'noCheckIn'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return childAttendancePage(Object.assign(parameter, this.queryParam)).then(res => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      imgTitle: '',
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      replaceFields: {
        title: 'name',
        value: 'id'
      },
      monthFormat: 'YYYY-MM'
    }
  },

  created() {
    this.getOrgTree()
    this.imgTitle = process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/previewImg?id='
    if (this.hasPerm('coursetype:edit') || this.hasPerm('coursetype:delete')) {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },

  methods: {
    getOrgTree() {
      sysPosList({ isArchived: false }).then(res => {
        if (!res.success) {
          return
        }
        let datas = res.data.map(item => {
          item.value = item.id
          return item
        })
        datas.unshift({ name: '全部', value: null })
        this.treeData = datas
      })
    },
    onChange(date, dateString) {
      console.log(date, dateString)
      this.queryParam.Month = dateString ? dateString : null
      this.$refs.table.refresh(true)
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
      this.queryParam.ClassIds = info.node.value
      this.$refs.table.refresh(true)
    },
    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ id: record.id }]
      this.sysPosDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map(d => {
        return { id: d }
      })
      this.sysPosDelete(paramIds)
    },
    /**
     * 删除
     */
    sysPosDelete(param) {
      courseTypeDelete(param)
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    changeStatus(record) {
      console.log(record)
    },
    /**
     * 批量导出
     */
     batchExport() {
      if (this.queryParam.Month == undefined || this.queryParam.Month == '') {
        return this.$message.error('请选择月份再操作')
      }
      const month = this.queryParam.Month.substr(5, 2)
      ChildrensRecordExport({ month: month }).then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>

<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.preview-img {
  display: inline-block;
  height: 50px;
}
</style>
